'use strict';
var vk; // 全局vk实例
// 涉及的表名
const dbName = require("../../../dao/config.js");

var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
	isCloudObject: true, // 标记为云对象模式
	/**
	 * 请求前处理，主要用于调用方法之前进行预处理，一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
	 */
	_before: async function() {
		vk = this.vk; // 将vk定义为全局对象
		// let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
	},
	/**
	 * 请求后处理，主要用于处理本次调用方法的返回结果或者抛出的错误
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
	 */
	_after: async function(options) {
		let { err, res } = options;
		if (err) {
			return; // 如果方法抛出错误，直接return;不处理
		}
		return res;
	},
	/**
	 * 审核
	 * @url admin/business/sys.withdrawal.examine 前端调用的url参数地址
	 */
	examine: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			_id, // 唯一标识
			mode, // 提现类型
			seller_remark = "", // 商家审核备注,通过和不通过要对应修改
			status, // 状态值
			sms = true, // true 发短信 false 不发短信
		} = data;
		// 参数非空检测
		// 参数非空检测
		let nullKey = vk.pubfn.isNullOneByObject({ _id, status, mode });
		if (nullKey) return { code: -1, msg: '参数 ' + nullKey + ' 不能为空' };

		let withdrawalRecInfo = await vk.daoCenter.withdrawalRecDao.findById(_id);

		if (vk.pubfn.isNull(withdrawalRecInfo)) {
			return { "code": -1, "msg": '提现订单不存在' }
		}
		if (withdrawalRecInfo.status !== 0) {
			return { "code": -1, "msg": '只有待提现订单才可操作!' }
		}
		let userInfo = await vk.daoCenter.userDao.findById(withdrawalRecInfo.user_id);
		if (vk.pubfn.isNull(userInfo)) {
			return { "code": -1, "msg": '提现用户不存在' }
		}
		// 事务开始
		const transaction = await vk.baseDao.startTransaction();
		try {
			// 审核
			let updateNum = await vk.baseDao.updateById({
				db: transaction,
				dbName: dbName.withdrawalRec,
				id: _id,
				dataJson: {
					mode, // 提现类型
					seller_remark, // 商家审核备注,通过和不通过要对应修改
					status, // 状态值
				}
			});
			let saas_service_fee = 0;
			if (updateNum > 0) {
				if (status === 2) {
					// 审核通过
					if (mode === 1) {
						// 执行真正的急速提现操作
						// mode=1 急速提现：通过API自动转账给用户（注意：银行卡不支持急速提现）
						// mode=0 普通提醒：财务手动转账给用户
						console.log(1, "开始急速提现");
						if (withdrawalRecInfo.withdrawal_info.type === 1) {
							// 提现到支付宝
							res = await vk.vkPay.transfer({
								account: withdrawalRecInfo.withdrawal_info.account_no,
								real_name: withdrawalRecInfo.withdrawal_info.name,
								amount: withdrawalRecInfo.withdrawal_money,
								title: "商城提现",
								pay_type: "alipay",
								remark: seller_remark || "商城提现",
								out_biz_no: withdrawalRecInfo.no
							});
						} else if (withdrawalRecInfo.withdrawal_info.type === 2) {
							// 提现到微信（需要开通商家转账到零钱的API）
							let openid;
							let payPlatform;
							let keys = [
								{ uniIdPlatform: "mp-weixin", payPlatform: "mp-weixin" },
								{ uniIdPlatform: "h5-weixin", payPlatform: "h5-weixin" },
								{ uniIdPlatform: "app-plus", payPlatform: "app-plus" },
								{ uniIdPlatform: "h5-web", payPlatform: "mweb" }
							]
							// 查找当前用户已绑定的微信类型
							for (let i = 0; i < keys.length; i++) {
								let item = keys[i];
								if (userInfo.wx_openid[item.uniIdPlatform]) {
									openid = userInfo.wx_openid[item.uniIdPlatform];
									payPlatform = item.payPlatform;
									break;
								}
							}
							
							if (!payPlatform) {
								throw new Error("msg:当前用户未绑定微信，无法使用急速提现");
							}

							res = await vk.vkPay.transfer({
								platform: payPlatform,
								openid: openid,
								real_name: withdrawalRecInfo.withdrawal_info.name,
								amount: withdrawalRecInfo.withdrawal_money,
								title: "商城提现",
								pay_type: "wxpay",
								remark: seller_remark || "商城提现",
								out_biz_no: withdrawalRecInfo.no,
								version: 3, // 固定3，代表使用v3版本
							});
						} else {
							// 异常
							throw new Error("msg:急速提现只能提现到支付宝或微信");
						}
						console.log(2, "转账结果", res);
						if (res.code !== 0) {
							console.log(-1, "事务开始回滚");
							return await vk.baseDao.rollbackTransaction({
								db: transaction,
								msg: res.msg
							});
						}
						// 向下取整
						saas_service_fee = Math.floor(withdrawalRecInfo.money * 0.004);
					}

				} else if (status === 4) {
					// 审核拒绝

					// 发送提现被拒绝的消息给客户
					// 如果审核不通过,需要退回可提现余额
					await vk.daoCenter.moneyDao.updateAccountRewardForTransaction({
						db: transaction,
						user_id: userInfo._id,
						value: withdrawalRecInfo.money,
						isAdd: true,
						no: withdrawalRecInfo.no,
						title: `提现拒绝，余额返还`,
						comment: ``,
						add_type: 10, // 1 人工录入 2 用户线上充值 3 消费 4 退款 5 转账 6 余额转换 7 奖励发放 8 解锁 9 提现 10 提现拒绝后返还
						updateTotal: false,
					});
				}
				// 发送消息
				let openid = vk.pubfn.getData(userInfo, "wx_openid.mp-weixin");
				if (openid) {
					// 发送微信小程序通知

				}
				if (sms && withdrawalRecInfo.withdrawal_info.mobile) {
					// 发送短信通知

				}
			}
			console.log(3, "准备提交事务");
			// 提交事物
			await transaction.commit();
			console.log(4, "事务提交成功");
		} catch (err) {
			// 事务回滚
			console.log(-1, "事务开始回滚");
			return await vk.baseDao.rollbackTransaction({
				db: transaction,
				err
			});
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 获取列表
	 * @url admin/business/sys.withdrawal.getList 前端调用的url参数地址
	 */
	getList: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		res = await vk.daoCenter.withdrawalRecDao.getTableData({
			data,
			foreignDB: [{
				dbName: dbName.user, // 副表名
				localKey: "user_id", // 主表外键字段名
				foreignKey: "_id", // 副表外键字段名
				as: "userInfo",
				limit: 1, // 当limit = 1时，以对象形式返回，否则以数组形式返回
			}]
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 获取未申请提现的用户列表
	 * @url admin/business/sys.withdrawal.getNotApplyUserList 前端调用的url参数地址
	 */
	getNotApplyUserList: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		res = await vk.daoCenter.userDao.getTableData({
			data,
			whereJson: _.and(_.or([{
					"account_reward.allow": _.gt(0)
				},
				{
					"account_reward.wait": _.gt(0)
				}
			])),
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 包含 未申请提现 已申请未提现 已申请已提现 累计奖励
	 * @url admin/business/sys.withdrawal.getTotal 前端调用的url参数地址
	 */
	getTotal: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			totalTime = []
		} = data;

		let whereJson = {};
		if (totalTime && totalTime[0] && totalTime[1]) {
			whereJson["_add_time"] = _.gte(totalTime[0]).lte(totalTime[1])
		}
		let m1 = 0;
		let m1Str = "";
		let m2 = 0;
		let m2Str = "";
		if (vk.pubfn.isNull(whereJson["_add_time"])) {
			// 未申请提现
			m1 = await vk.baseDao.sum({
				dbName: dbName.user,
				fieldName: "account_reward.wait",
				whereJson: {
					...whereJson,
					"account_reward.wait": _.gt(0)
				}
			});
			m1Str = vk.pubfn.toDecimal(m1 / 100, 2) + " 元";
			m2 = await vk.baseDao.sum({
				dbName: dbName.user,
				fieldName: "account_reward.allow",
				whereJson: {
					...whereJson,
					"account_reward.allow": _.gt(0)
				}
			});
			m2Str = vk.pubfn.toDecimal(m2 / 100, 2) + " 元";
		} else {
			m1Str = "此项不支持按时间查询";
			m2Str = "此项不支持按时间查询";
		}


		// 已申请未提现
		let m3 = await vk.baseDao.sum({
			dbName: dbName.withdrawalRec,
			fieldName: "money",
			whereJson: {
				...whereJson,
				status: 0,
				//money : _.gt(0),
			}
		});
		// 已申请已提现
		let m4 = await vk.baseDao.sum({
			dbName: dbName.withdrawalRec,
			fieldName: "money",
			whereJson: {
				...whereJson,
				status: 2,
			}
		});
		// 累计奖励
		let m0 = m1 + m2 + m3 + m4;

		res.m0 = vk.pubfn.toDecimal(m0 / 100, 2);
		res.m1 = vk.pubfn.toDecimal(m1 / 100, 2);
		res.m2 = vk.pubfn.toDecimal(m2 / 100, 2);
		res.m3 = vk.pubfn.toDecimal(m3 / 100, 2);
		res.m4 = vk.pubfn.toDecimal(m4 / 100, 2);
		res.m1Str = m1Str;
		res.m2Str = m2Str;

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 修改审核备注
	 * @url admin/business/sys.withdrawal.updateSellerRemark 前端调用的url参数地址
	 */
	updateSellerRemark: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			_id, // 唯一标识
			seller_remark, // 商家审核备注,通过和不通过要对应修改
		} = data;
		// 参数非空检测
		if (vk.pubfn.isNull(_id)) {
			return { code: -1, msg: '参数错误' };
		}
		let withdrawalRecInfo = await vk.daoCenter.withdrawalRecDao.findById(_id);
		if (vk.pubfn.isNull(withdrawalRecInfo)) return { "code": -1, "msg": '提现订单不存在' }
		// 执行数据库API请求
		await vk.daoCenter.withdrawalRecDao.updateById(_id, {
			seller_remark
		});
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},

	/**
	 * 模板函数
	 * @url admin/business/sys.withdrawal.test 前端调用的url参数地址
	 */
	test: async function(data) {
		let res = { code: 0, msg: '' };
		// 业务逻辑开始-----------------------------------------------------------


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
};

module.exports = cloudObject;
